package bimvu.yolaguidebook;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.ArrayList;


public class ListOfSitesActivity extends Activity {

    private static final String SITE_TAG_NAME = "site";
    private static final String TITLE_TAG_NAME = "title";
    private static final String DESCRIPTION_TAG_NAME = "description";
    private static final String ADDRESS_TAG_NAME = "address";
    private static final String LATITUDE_TAG_NAME = "latitude";
    private static final String LONGTITUDE_TAG_NAME = "longtitude";
    private static final String THUMB_TAG_NAME = "thumb";
    private static final String MAIN_PHOTO_TAG_NAME = "mainPhoto";

    private ArrayList<Site> sites;
    private String locationProvider;
    private SiteRowAdapter siteRowAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_of_sites);

        ListView urlListView = (ListView) findViewById(R.id.listView);

        sites = getSites();
        siteRowAdapter = new SiteRowAdapter(this, sites);
        urlListView.setAdapter(siteRowAdapter);

        final Context thisContext = this;

        urlListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                final Site site = sites.get(i);
                Intent intent = new Intent(thisContext, SiteActivity.class);
                intent.putExtra(Site.class.toString(), site);
                startActivity(intent);
            }
        });

        setupLocationManagement();
    }

    private void setupLocationManagement() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);

        locationProvider = locationManager.getBestProvider(criteria, true);


        Location location = locationManager.getLastKnownLocation(locationProvider);
        recalculateDistanceToSites(location);


        LocationListener locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                recalculateDistanceToSites(location);
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {

            }
        };

        locationManager.requestLocationUpdates(locationProvider, 5000, 5, locationListener);
    }

    private void recalculateDistanceToSites(Location location) {
        if (location != null) {
            for (Site site : sites) {
                Location destination = new Location(locationProvider);
                destination.setLatitude(site.latitude);
                destination.setLongitude(site.longtitude);

                site.distance = location.distanceTo(destination);
            }
            siteRowAdapter.notifyDataSetChanged();
        }
    }

    private ArrayList<Site> getSites() {
        final ArrayList<Site> sites = new ArrayList<Site>();

        try {
            Resources resources = getResources();
            XmlResourceParser xmlResourceParser = resources.getXml(R.xml.sites);
            Site site = null;
            int eventType = xmlResourceParser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                if (eventType == XmlPullParser.START_TAG) {
                    String tagName = xmlResourceParser.getName();
                    if (tagName.equalsIgnoreCase(SITE_TAG_NAME)) {
                        site = new Site();
                    } else if (site != null) {
                        if (tagName.equalsIgnoreCase(TITLE_TAG_NAME)) {
                            site.title = xmlResourceParser.nextText();
                        } else if (tagName.equalsIgnoreCase(DESCRIPTION_TAG_NAME)) {
                            site.description = xmlResourceParser.nextText();
                        } else if (tagName.equalsIgnoreCase(ADDRESS_TAG_NAME)) {
                            site.address = xmlResourceParser.nextText();
                        } else if (tagName.equalsIgnoreCase(LATITUDE_TAG_NAME)) {
                            site.latitude = Double.parseDouble(xmlResourceParser.nextText());
                        } else if (tagName.equalsIgnoreCase(LONGTITUDE_TAG_NAME)) {
                            site.longtitude = Double.parseDouble(xmlResourceParser.nextText());
                        } else if (tagName.equalsIgnoreCase(THUMB_TAG_NAME)) {
                            site.thumbKey = xmlResourceParser.nextText();
                        } else if (tagName.equalsIgnoreCase(MAIN_PHOTO_TAG_NAME)) {
                            site.mainPhotoKey = xmlResourceParser.nextText();
                        }
                    }
                } else if (eventType == XmlPullParser.END_TAG) {
                    String tagName = xmlResourceParser.getName();
                    if (tagName.equalsIgnoreCase(SITE_TAG_NAME) && (site != null)) {
                        sites.add(site);
                    }
                }
                eventType = xmlResourceParser.next();
            }
            xmlResourceParser.close();
        } catch (Resources.NotFoundException notFoundException) {
            //do nothing
        } catch (XmlPullParserException xmlPullParserException) {
            //do nothing
        } catch (IOException ioException) {
            //do nothing
        }
        return sites;
    }
}
